{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# costas_array"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/costas_array.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/costas_array.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Costas array in Google CP Solver.\n",
    "\n",
    "  From http://mathworld.wolfram.com/CostasArray.html:\n",
    "  '''\n",
    "  An order-n Costas array is a permutation on {1,...,n} such\n",
    "  that the distances in each row of the triangular difference\n",
    "  table are distinct. For example, the permutation {1,3,4,2,5}\n",
    "  has triangular difference table {2,1,-2,3}, {3,-1,1}, {1,2},\n",
    "  and {4}. Since each row contains no duplications, the permutation\n",
    "  is therefore a Costas array.\n",
    "  '''\n",
    "\n",
    "  Also see\n",
    "  http://en.wikipedia.org/wiki/Costas_array\n",
    "\n",
    "  About this model:\n",
    "  This model is based on Barry O'Sullivan's model:\n",
    "  http://www.g12.cs.mu.oz.au/mzn/costas_array/CostasArray.mzn\n",
    "\n",
    "  and my small changes in\n",
    "  http://hakank.org/minizinc/costas_array.mzn\n",
    "\n",
    "  Since there is no symmetry breaking of the order of the Costas\n",
    "  array it gives all the solutions for a specific length of\n",
    "  the array, e.g. those listed in\n",
    "  http://mathworld.wolfram.com/CostasArray.html\n",
    "\n",
    "  1     1       (1)\n",
    "  2     2       (1, 2), (2,1)\n",
    "  3     4       (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2)\n",
    "  4     12      (1, 2, 4, 3), (1, 3, 4, 2), (1, 4, 2, 3), (2, 1, 3, 4),\n",
    "                (2, 3, 1, 4), (2, 4, 3, 1), (3, 1, 2, 4), (3, 2, 4, 1),\n",
    "                (3, 4, 2, 1), (4, 1, 3, 2), (4, 2, 1, 3), (4, 3, 1, 2)\n",
    "  ....\n",
    "\n",
    "  See http://www.research.att.com/~njas/sequences/A008404\n",
    "  for the number of solutions for n=1..\n",
    "  1, 2, 4, 12, 40, 116, 200, 444, 760, 2160, 4368, 7852, 12828,\n",
    "  17252, 19612, 21104, 18276, 15096, 10240, 6464, 3536, 2052,\n",
    "  872, 200, 88, 56, 204,...\n",
    "\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "def main(n=6):\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver(\"Costas array\")\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "  print(\"n:\", n)\n",
    "\n",
    "  #\n",
    "  # declare variables\n",
    "  #\n",
    "  costas = [solver.IntVar(1, n, \"costas[%i]\" % i) for i in range(n)]\n",
    "  differences = {}\n",
    "  for i in range(n):\n",
    "    for j in range(n):\n",
    "      differences[(i, j)] = solver.IntVar(-n + 1, n - 1,\n",
    "                                          \"differences[%i,%i]\" % (i, j))\n",
    "  differences_flat = [differences[i, j] for i in range(n) for j in range(n)]\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "\n",
    "  # Fix the values in the lower triangle in the\n",
    "  # difference matrix to -n+1. This removes variants\n",
    "  # of the difference matrix for the same Costas array.\n",
    "  for i in range(n):\n",
    "    for j in range(i + 1):\n",
    "      solver.Add(differences[i, j] == -n + 1)\n",
    "\n",
    "  # hakank: All the following constraints are from\n",
    "  # Barry O'Sullivans's original model.\n",
    "  #\n",
    "  solver.Add(solver.AllDifferent(costas))\n",
    "\n",
    "  # \"How do the positions in the Costas array relate\n",
    "  #  to the elements of the distance triangle.\"\n",
    "  for i in range(n):\n",
    "    for j in range(n):\n",
    "      if i < j:\n",
    "        solver.Add(differences[(i, j)] == costas[j] - costas[j - i - 1])\n",
    "\n",
    "  # \"All entries in a particular row of the difference\n",
    "  #  triangle must be distint.\"\n",
    "  for i in range(n - 2):\n",
    "    solver.Add(\n",
    "        solver.AllDifferent([differences[i, j] for j in range(n) if j > i]))\n",
    "\n",
    "  #\n",
    "  # \"All the following are redundant - only here to speed up search.\"\n",
    "  #\n",
    "\n",
    "  # \"We can never place a 'token' in the same row as any other.\"\n",
    "  for i in range(n):\n",
    "    for j in range(n):\n",
    "      if i < j:\n",
    "        solver.Add(differences[i, j] != 0)\n",
    "\n",
    "  for k in range(2, n):\n",
    "    for l in range(2, n):\n",
    "      if k < l:\n",
    "        solver.Add(differences[k - 2, l - 1] + differences[k, l] ==\n",
    "                   differences[k - 1, l - 1] + differences[k - 1, l])\n",
    "\n",
    "  #\n",
    "  # search and result\n",
    "  #\n",
    "  db = solver.Phase(costas + differences_flat, solver.CHOOSE_FIRST_UNBOUND,\n",
    "                    solver.ASSIGN_MIN_VALUE)\n",
    "\n",
    "  solver.NewSearch(db)\n",
    "  num_solutions = 0\n",
    "  while solver.NextSolution():\n",
    "    print(\"costas:\", [costas[i].Value() for i in range(n)])\n",
    "    print(\"differences:\")\n",
    "    for i in range(n):\n",
    "      for j in range(n):\n",
    "        v = differences[i, j].Value()\n",
    "        if v == -n + 1:\n",
    "          print(\"  \", end=\" \")\n",
    "        else:\n",
    "          print(\"%2d\" % v, end=\" \")\n",
    "      print()\n",
    "    print()\n",
    "    num_solutions += 1\n",
    "\n",
    "  solver.EndSearch()\n",
    "\n",
    "  print()\n",
    "  print(\"num_solutions:\", num_solutions)\n",
    "  print(\"failures:\", solver.Failures())\n",
    "  print(\"branches:\", solver.Branches())\n",
    "  print(\"WallTime:\", solver.WallTime())\n",
    "\n",
    "\n",
    "n = 6\n",
    "if len(sys.argv) > 1:\n",
    "  n = int(sys.argv[1])\n",
    "main(n)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
